<template>
  <div class="">
    <div v-if="showFileList">
      <el-upload
        class=""
        :file-list="fileList"
        :show-file-list="showFileList"
        :limit="limit"
        :accept="accept"
        list-type="picture-card"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :on-preview="uploadPreview"
        :on-remove="uploadRemove"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <i :class="uploadIcon"></i>
      </el-upload>
    </div>
    <div v-else>
      <el-upload
        v-if="isButton"
        class=""
        :show-file-list="showFileList"
        :accept="accept"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <el-button type="primary" icon="el-icon-upload">{{
          buttonText
        }}</el-button>
      </el-upload>
      <el-upload
        v-else
        class="single-image-uploader"
        :show-file-list="showFileList"
        :accept="accept"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <i
          slot="trigger"
          :class="uploadIcon + ' single-image-uploader-icon'"
        ></i>
        <div
          v-if="isShowFile && single_file_url"
          class="Img"
          style="
            position: relative;
            display: inline-block;
            margin-left: 10px;
            width: 90px;
            height: 90px;
          "
        >
          <div class="closeImg">
            <i class="el-icon-delete" @click.stop="del"></i>
          </div>
          <el-image
            :src="single_file_url"
            class="single-image"
            fit="contain"
          ></el-image>
        </div>
        <div slot="tip" class="el-upload__tip">
          {{ tipText }}
        </div>
      </el-upload>
    </div>

    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
      <el-image
        width="100%"
        :src="dialogImageUrl"
        alt=""
        fit="contain"
      ></el-image>
      <!-- <img width="100%" :src="dialogImageUrl" alt="" mode="aspectFit" /> -->
    </el-dialog>
  </div>
</template>

<script>
import { getAdminToken } from "@/utils/auth";
import { uploadURL } from "@/api/admin/common";

export default {
  name: "FileUpload",
  props: {
    tipText: {
      type: String,
      default() {
        return "";
      },
    },
    // 多文件
    fileList: {
      type: Array,
      default() {
        return [];
      },
    },
    // 单文件
    singleFile: {
      type: Object,
      default() {
        return {
          url: "",
          path: "",
        };
      },
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: true,
    },
    // 多文件上传数量
    limit: {
      type: Number,
      default: 9,
    },
    // 上传图片大小最大限制(单位：KB)
    imageMaxSize: {
      type: Number,
      default: 5120,
    },
    // 上传文件大小最大限制(单位：M)
    maxSize: {
      type: Number,
      default: 100,
    },
    // 上传文件类型
    accept: {
      type: String,
      default: "image/jpeg, image/png, image/gif",
    },
    uploadData: {
      type: Object,
      default() {
        return {
          folder: "local",
          place: "",
          multi: this.showFileList,
          total_count: this.limit,
          count: 0,
        };
      },
    },
    uploadIcon: {
      type: String,
      default: "el-icon-plus",
    },
    // 是否要显示文件
    isShowFile: {
      type: Boolean,
      default: true,
    },
    // 是否按钮上传
    isButton: {
      type: Boolean,
      default: false,
    },
    // 按钮上传对应按钮名称
    buttonText: {
      type: String,
      default: "选择文件",
    },
  },
  data() {
    return {
      loading: "",
      /*fileList: [
        //{name:'', url: ''}
      ],*/
      single_file_url: "",

      uploadHeaders: { token: getAdminToken() },
      uploadAction: uploadURL(), // 文件上传地址
      /*uploadData: {
        type: 'image'
      },*/
      dialogImageVisible: false,
      dialogImageUrl: "",
    };
  },
  watch: {
    singleFile: function (val, oldval) {
      //console.log(val, oldval)
      if (val) {
        this.single_file_url = val.url;
      }
    },
  },
  created() {
    //console.log(this.fileList)
    if (this.singleFile && this.singleFile.url) {
      this.single_file_url = this.singleFile.url;
    }
  },
  methods: {
    uploadBefore(file) {
      this.loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // let extArr = this.accept.split(",");
      const imageAccept = "image/jpeg, image/png, image/gif";
      // const imageAccept = this.accept;
      const isFileExt = this.accept.includes(file.type);
      let isFileSize = true;
      if (!isFileExt) {
        this.loading.close();
        this.$messages.warning("请上传" + this.accept + "文件");
      } else {
        if (file.type && imageAccept.includes(file.type)) {
          isFileSize = file.size / 1024 < this.imageMaxSize;
          if (!isFileSize) {
            this.loading.close();
            this.$messages.warning(
              "文件大小不能超过 " + 5 + "MB!"
              // "图片大小不能超过 " + this.imageMaxSize + "KB!"
            );
          }
        } else {
          isFileSize = file.size / 1024 / 1024 < this.maxSize;
          if (!isFileSize) {
            this.loading.close();
            this.$messages.warning("文件大小不能超过 " + this.maxSize + "M!");
          }
        }
      }

      return isFileExt && isFileSize;
    },
    uploadSuccess(res, file) {
      if (res.status === 1) {
        if (this.showFileList) {
          this.fileList.push({
            id: new Date().getTime(),
            name: "",
            url: res.data.full_filepath,
            path: res.data.filepath,
          });
        } else {
          if (this.isShowFile) {
            this.single_file_url = res.data.full_filepath;
          }
          this.singleFile.url = res.data.full_filepath;
          //this.singleFile.url = URL.createObjectURL(file.raw)
          this.singleFile.path = res.data.filepath;
        }

        this.uploadCBK();
        this.loading.close();
        this.$messages.success(res.msg);
      } else {
        this.loading.close();
        this.$messages.error(res.msg);
      }
    },
    uploadError(res) {
      this.loading.close();
      this.$messages.error(res.msg || "上传出错");
    },
    uploadRemove(file, fileList) {
      //this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
      var index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      this.uploadCBK();
    },
    uploadPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },

    // 上传回调
    uploadCBK() {
      //console.log(this.fileList)
      if (this.showFileList) {
        this.$emit("uploadCallback", this.fileList);
      } else {
        this.$emit("uploadCallback", this.singleFile);
      }
    },
    del() {
      this.singleFile = {};
      this.$emit("uploadCallback", this.singleFile);
      // console.log(this.singleFile);
    },
  },
};
</script>
<style lang="scss" scoped>
.Img:hover {
  .closeImg {
    z-index: 2;
  }
}
.closeImg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: -1;
  background-color: #00000050;
  border-radius: 5px;
  text-align: center;
  line-height: 90px;
  color: #ffff;
  i {
    cursor: pointer;
  }
}
</style>
